<template>
  <a-modal
    :maskClosable="false"
    title="接入动环"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-item label="名称">
          <a-input
            autocomplete="off"
            v-decorator="['name', decoratorOptions.name]"
          />
        </a-form-item>
        <a-form-item label="类型">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['type', decoratorOptions.type]"
          >
            <a-select-option
              v-for="(t, index) in typeList"
              :key="index"
              :value="t.value"
            >
              {{ t.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="访问IP">
          <a-input
            autocomplete="off"
            v-decorator="['hostIp', decoratorOptions.hostIp]"
          />
        </a-form-item>
        <a-form-item label="访问端口">
          <a-input
            autocomplete="off"
            @keyup="clearNoNum('port')"
            @blur="clearNoNum('port')"
            v-decorator="['port', decoratorOptions.port]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { gPostAction } from "@/api/manage";
import { filterNoNum } from "@/utils/util";
export default {
  name: "DhModal",
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      initObj: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      typeList: [
        {
          name: "北京盈泽动环系统",
          value: "supervision_system_yingze",
        },
        {
          name: "江苏大华动环系统",
          value: "supervision_system_dahua",
        },
      ],
      decoratorOptions: {
        name: {
          rules: [
            { required: true, message: "请输入名称" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
          ],
        },
        type: {
          rules: [{ required: true, message: "请选择类型" }],
        },
        hostIp: {
          rules: [
            { required: true, message: "请输入访问IP" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.isValidIp() },
          ],
        },
        port: {
          rules: [
            { required: true, message: "请输入访问端口" },
            {
              validator: this.validators.xmax({ max: 65535 }),
              trigger: "blur",
            },
            { validator: this.validators.xmin({ min: 0 }), trigger: "blur" },
          ],
        },
      },
    };
  },
  computed: {
    getTypeNameList() {
      const list = []
      this.typeList.forEach((d) => {
        list.push(d.value)
      })
      return list
    }
  },
  methods: {
    clearNoNum(fieldName) {
      let obj = {};
      obj[fieldName] = filterNoNum(this.form.getFieldValue(fieldName));
      this.form.setFieldsValue(obj);
      this.form.validateFields([fieldName], (errors, values) => {});
    },
    loadSupplierList(record) {
      this.initObj = {};
      gPostAction("/supplier/list", { datacenterId: record.id }).then((res) => {
        if (res.success && res.data) {
          res.data.forEach((element) => {
            if (element && this.getTypeNameList.indexOf(element.type) > -1) {
              this.initObj = element;
              let configObj = {};
              if (element.config) {
                configObj = JSON.parse(element.config)
              }
              this.form.setFieldsValue({
                name: element.name,
                type: element.type,
                hostIp: configObj.hostIp || undefined,
                port: configObj.port || undefined,
              });
            }
          });
        }
      });
    },
    config(record) {
      this.form.resetFields();
      this.loadSupplierList(record);
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          let postData = {
            datacenterId: this.model.id,
            name: values.name,
            type: values.type,
            config: JSON.stringify({
              hostIp: values.hostIp,
              port: values.port + "",
            }),
          };

          let postUrl = "/supplier/create";
          if (this.initObj && this.initObj.id) {
            postUrl = "/supplier/update";
            postData.id = this.initObj.id;
          }
          gPostAction(postUrl, postData)
            .then((res) => {
              if (res.success) {
                this.$emit("ok");
              }
            })
            .finally(() => {
              this.confirmLoading = false;
              this.handleCancel();
            });
        }
      });
    },
    handleCancel(e) {
      this.visible = false;
    },
  },
};
</script>
